package com.ruoyi.socket.gateway;

import com.ruoyi.socket.gateway.pool.ChannelPool;
import com.ruoyi.socket.gateway.pool.NettyChannel;
import com.ruoyi.socket.util.ByteBufStringUtils;
import io.netty.buffer.ByteBuf;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

/***
 *  @description
 *  @author zhao
 *  @date: 2020/6/13
 *  @version: v1.0
 */
public class NettyClientPool {

    private static NettyClientPool nettyClientPool;
    private static ChannelPool channelPool;

    private NettyClientPool(String host,Integer port) {

        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setMaxIdle(10);//最大活跃数
        config.setMinIdle(1);//最小活跃数
        config.setMaxTotal(100);//最大总数
        //创建资源池
        channelPool = new ChannelPool(config, host, port);
    }

    public static synchronized NettyClientPool getInstance(String host,Integer port) {
        if (nettyClientPool == null) {
            nettyClientPool = new NettyClientPool(host,port);
        }
        return nettyClientPool;
    }


    public String sendMsg(String msg) {
        //获取连接
        NettyChannel nettyChannel = channelPool.getResource();
        //发送消息
        nettyChannel.getCh().writeAndFlush(msg);
        ByteBuf buffer = nettyChannel.getCh().alloc().buffer();
        String result = ByteBufStringUtils.convertByteBufToString(buffer);
        System.out.println("接收到业务数据... " + result);
        //回收资源
        channelPool.returnResource(nettyChannel);
        return result;

    }


}
